package com.example.itcacp.repository.mybatis;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.itcacp.entity.Content;
import com.example.itcacp.entity.Category;
import com.example.itcacp.entity.Like;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository
public interface ContentMapper extends BaseMapper<Content> {

    /**
     * 查询数据库中的所有内容，并通过多表查询，通过categoryId连接分类表(tc_category)查询内容所对应分类
     * 以及对于文章标签，通过内容与标签联合表（tc_content_tag），将内容与标签联系起来
     * */
    @Select ( "SELECT * FROM tc_content WHERE " +
            "content_type = #{contentType} ORDER BY created_at DESC" )
    @Results({
            @Result(property = "contentId", column = "content_id"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "title", column = "title"),
            @Result(property = "content", column = "content"),
            @Result(property = "contentType", column = "content_type"),
            @Result(property = "cover", column = "cover"),
            @Result(property = "categoryId", column = "category_id"),
            @Result(property = "tags", column = "tags"),
            @Result(property = "created_at", column = "created_at"),
            @Result(property = "updated_at", column = "updated_at"),
            @Result(property = "category", column = "category_id", javaType = Category.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.ContentMapper.selectCategoryById")),
            @Result(property = "user", column = "user_id", javaType = String.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.UserMapper.findBolgUserById")),
            @Result(property = "likes", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.LikeMapper.findLikes")),
            @Result(property = "collections", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.CollectMapper.findCollect")),
            @Result(property = "views", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.BrowseHistoryMapper.findBrowseHistory"))
    })
    List<Content> selectContentAll(Like.ContentType contentType);

    @Select("SELECT * FROM tc_category WHERE category_id = #{categoryId}")
    Category selectCategoryById(Long categoryId);    // 查询对应分类

    /**
     * 内容作者其他同类型作品查询
     * */
    @Select ( "SELECT * FROM tc_content WHERE " +
            "content_type = #{contentType} AND user_id = #{userId} ORDER BY created_at DESC" )
    List<Content> selectContentAllByUser(Like.ContentType contentType, Long userId);

    /**
     * 查询内容详情
     * */
    @Select ( "SELECT * FROM tc_content " +
            "WHERE content_id = #{contentId} AND content_type = #{contentType}")
    @Results({
            @Result(property = "contentId", column = "content_id"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "title", column = "title"),
            @Result(property = "content", column = "content"),
            @Result(property = "contentType", column = "content_type"),
            @Result(property = "cover", column = "cover"),
            @Result(property = "categoryId", column = "category_id"),
            @Result(property = "tags", column = "tags"),
            @Result(property = "created_at", column = "created_at"),
            @Result(property = "updated_at", column = "updated_at"),
            @Result(property = "category", column = "category_id", javaType = Category.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.ContentMapper.selectCategoryById")),
            @Result(property = "user", column = "user_id", javaType = String.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.UserMapper.findBolgUserById")),
            @Result(property = "likes", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.LikeMapper.findLikes")),
            @Result(property = "collections", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.CollectMapper.findCollect")),
            @Result(property = "views", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.BrowseHistoryMapper.findBrowseHistory")),
            @Result(property = "comment", column = "{contentId=content_id,contentType=content_type}", javaType = List.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.CommentMapper.findTopLevelComments"))
    })
    Content findContentByIdType(Long contentId, Like.ContentType contentType);


    /**
     * 内容添加
     * */
    @Insert ( "INSERT INTO tc_content " +
            "( user_id, title, content, content_type, tags, category_id, cover, created_at) VALUES " +
            "(#{userId}, #{title}, #{content}, #{contentType}, #{tags}, #{categoryId}, #{cover}, #{created_at})")
    @Options(useGeneratedKeys = true, keyProperty = "contentId") // 自动填充刚插入记录的主键值到传入的对象属性中。
    void add(Content content);

    /**
     * 根据ID列表批量查询内容
     * @param contentIds 内容ID列表
     * @return 内容列表
     */
    @Results({
            @Result(property = "contentId", column = "content_id"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "title", column = "title"),
            @Result(property = "content", column = "content"),
            @Result(property = "contentType", column = "content_type"),
            @Result(property = "cover", column = "cover"),
            @Result(property = "categoryId", column = "category_id"),
            @Result(property = "tags", column = "tags"),
            @Result(property = "created_at", column = "created_at"),
            @Result(property = "updated_at", column = "updated_at"),
            @Result(property = "category", column = "category_id", javaType = Category.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.ContentMapper.selectCategoryById")),
            @Result(property = "user", column = "user_id", javaType = String.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.UserMapper.findBolgUserById")),
            @Result(property = "likes", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.LikeMapper.findLikes")),
            @Result(property = "collections", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.CollectMapper.findCollect")),
            @Result(property = "views", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.BrowseHistoryMapper.findBrowseHistory")),
            @Result(property = "comment", column = "{contentId=content_id,contentType=content_type}", javaType = List.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.CommentMapper.findTopLevelComments"))
    })
    @SelectProvider(type = ContentSqlProvider.class, method = "selectBatchByIdsSql")
    List<Content> selectBatchIds(@Param("contentIds") List<Long> contentIds);


    class ContentSqlProvider {
        public String selectBatchByIdsSql(Map<String, Object> params) {
            List<Long> contentIds = (List<Long>) params.get("contentIds");
            // 构建基础SQL
            StringBuilder sql = new StringBuilder();
            sql.append("SELECT\n")
                    .append("   *\n")
                    .append("FROM tc_content c\n")
                    .append("WHERE c.content_id IN (");
            // 动态生成ID列表占位符
            for (int i = 0; i < contentIds.size(); i++) {
                sql.append("#{contentIds[").append(i).append("]}");
                if (i < contentIds.size() - 1) {
                    sql.append(",");
                }
            }
            sql.append(")");
            return sql.toString();
        }
    }


    @Select ( "SELECT * FROM itcacp.tc_content WHERE user_id = #{userId}" )
    @Results({
            @Result(property = "contentId", column = "content_id"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "title", column = "title"),
            @Result(property = "content", column = "content"),
            @Result(property = "contentType", column = "content_type"),
            @Result(property = "cover", column = "cover"),
            @Result(property = "categoryId", column = "category_id"),
            @Result(property = "tags", column = "tags"),
            @Result(property = "created_at", column = "created_at"),
            @Result(property = "updated_at", column = "updated_at"),
            @Result(property = "category", column = "category_id", javaType = Category.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.ContentMapper.selectCategoryById")),
            @Result(property = "user", column = "user_id", javaType = String.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.UserMapper.findBolgUserById")),
            @Result(property = "likes", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.LikeMapper.findLikes")),
            @Result(property = "collections", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.CollectMapper.findCollect")),
            @Result(property = "views", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.BrowseHistoryMapper.findBrowseHistory")),
    })
    List<Content> selectContentAllByUserId(Long userId);


    //内容模糊查询
    @Select ( "SELECT * FROM itcacp.tc_content WHERE user_id = #{userId} " +
            "AND content like CONCAT('%',#{content}, '%')" )   // 模糊查询，合并查询条件
    @Results({
            @Result(property = "contentId", column = "content_id"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "title", column = "title"),
            @Result(property = "content", column = "content"),
            @Result(property = "contentType", column = "content_type"),
            @Result(property = "cover", column = "cover"),
            @Result(property = "categoryId", column = "category_id"),
            @Result(property = "tags", column = "tags"),
            @Result(property = "created_at", column = "created_at"),
            @Result(property = "updated_at", column = "updated_at"),
            @Result(property = "category", column = "category_id", javaType = Category.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.ContentMapper.selectCategoryById")),
            @Result(property = "user", column = "user_id", javaType = String.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.UserMapper.findBolgUserById")),
            @Result(property = "likes", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.LikeMapper.findLikes")),
            @Result(property = "collections", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.CollectMapper.findCollect")),
            @Result(property = "views", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.BrowseHistoryMapper.findBrowseHistory")),
    })
    List<Content> searchContent(String content, Long userId);


    @Select ( "SELECT * FROM itcacp.tc_content " +
            "WHERE content like CONCAT('%',#{query}, '%')" +
            "   OR title LIKE CONCAT('%',#{query},'%') " +
            "ORDER BY CASE WHEN content LIKE CONCAT('%',#{query},'%') THEN 1 ELSE 2 END"
    )   // 模糊查询，合并查询条件, 使用 OR 条件同时查询两个字段
    @Results({
            @Result(property = "contentId", column = "content_id"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "title", column = "title"),
            @Result(property = "content", column = "content"),
            @Result(property = "contentType", column = "content_type"),
            @Result(property = "cover", column = "cover"),
            @Result(property = "categoryId", column = "category_id"),
            @Result(property = "tags", column = "tags"),
            @Result(property = "created_at", column = "created_at"),
            @Result(property = "updated_at", column = "updated_at"),
            @Result(property = "category", column = "category_id", javaType = Category.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.ContentMapper.selectCategoryById")),
            @Result(property = "user", column = "user_id", javaType = String.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.UserMapper.findBolgUserById")),
            @Result(property = "likes", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.LikeMapper.findLikes")),
            @Result(property = "collections", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.CollectMapper.findCollect")),
            @Result(property = "views", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.BrowseHistoryMapper.findBrowseHistory")),
    })
    List<Content> search(String query);

    @Select ( "SELECT * FROM itcacp.tc_content" )
    @Results({
            @Result(property = "contentId", column = "content_id"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "title", column = "title"),
            @Result(property = "content", column = "content"),
            @Result(property = "contentType", column = "content_type"),
            @Result(property = "cover", column = "cover"),
            @Result(property = "categoryId", column = "category_id"),
            @Result(property = "tags", column = "tags"),
            @Result(property = "created_at", column = "created_at"),
            @Result(property = "updated_at", column = "updated_at"),
            @Result(property = "category", column = "category_id", javaType = Category.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.ContentMapper.selectCategoryById")),
            @Result(property = "user", column = "user_id", javaType = String.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.UserMapper.findBolgUserById")),
            @Result(property = "likes", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.LikeMapper.findLikes")),
            @Result(property = "collections", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.CollectMapper.findCollect")),
            @Result(property = "views", column = "{contentId=content_id,contentType=content_type}", javaType = Long.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.BrowseHistoryMapper.findBrowseHistory")),
    })
    List<Content> selectContents();



    /**
     * 查询内容详情
     * */
    @Select ( "SELECT * FROM tc_content " +
            "WHERE content_id = #{contentId}")
    @Results({
            @Result(property = "contentId", column = "content_id"),
            @Result(property = "title", column = "title"),
            @Result(property = "content", column = "content"),
            @Result(property = "contentType", column = "content_type"),
    })
    Content findContentById(Long contentId);
}